package com.ruoyi.system.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ElectronicReceipt;
import com.ruoyi.system.service.IElectronicReceiptService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 电汇回执单Controller
 *
 * @author zk
 * @date 2025-09-23
 */
@RestController
@RequestMapping("/system/receipt")
public class ElectronicReceiptController extends BaseController {
    @Autowired
    private IElectronicReceiptService electronicReceiptService;

    /**
     * 查询电汇回执单列表
     */
    @PreAuthorize("@ss.hasPermi('system:receipt:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElectronicReceipt electronicReceipt) {
        startPage();
        List<ElectronicReceipt> list = electronicReceiptService.selectElectronicReceiptList(electronicReceipt);
        return getDataTable(list);
    }

    /**
     * 导出电汇回执单列表
     */
    @PreAuthorize("@ss.hasPermi('system:receipt:export')")
    @Log(title = "电汇回执单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElectronicReceipt electronicReceipt) {
        List<ElectronicReceipt> list = electronicReceiptService.selectElectronicReceiptList(electronicReceipt);
        ExcelUtil<ElectronicReceipt> util = new ExcelUtil<ElectronicReceipt>(ElectronicReceipt.class);
        util.exportExcel(response, list, "电汇回执单数据");
    }

    /**
     * 获取电汇回执单详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:receipt:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(electronicReceiptService.selectElectronicReceiptById(id));
    }

    /**
     * 新增电汇回执单
     */
    @PreAuthorize("@ss.hasPermi('system:receipt:add')")
    @Log(title = "电汇回执单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElectronicReceipt electronicReceipt) {
        return toAjax(electronicReceiptService.insertElectronicReceipt(electronicReceipt));
    }

    /**
     * 修改电汇回执单
     */
    @PreAuthorize("@ss.hasPermi('system:receipt:edit')")
    @Log(title = "电汇回执单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElectronicReceipt electronicReceipt) {
        return toAjax(electronicReceiptService.updateElectronicReceipt(electronicReceipt));
    }

    /**
     * 删除电汇回执单
     */
    @PreAuthorize("@ss.hasPermi('system:receipt:remove')")
    @Log(title = "电汇回执单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(electronicReceiptService.deleteElectronicReceiptByIds(ids));
    }

    /**
     * 下载电汇回执单文件
     *
     * @param fileName 文件名
     * @param response 响应对象，用于输出文件流
     */
    @GetMapping("/download")
    @PreAuthorize("@ss.hasPermi('system:receipt:download')") // 权限控制
    public void download(@RequestParam String fileName, HttpServletResponse response) {
        try {
            // 1. 拼接文件存储路径（示例：假设文件存在服务器指定目录）
            String filePath = "D:/huidan/download/" + fileName;
            File file = new File(filePath);

            // 2. 判断文件是否存在
            if (file.exists()) {
                // 3. 设置响应头（指定为二进制流、附件下载、文件名编码）
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
                // 4. 复制文件流到响应输出流
                FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
            } else {
                // 文件不存在时，返回提示
                response.setContentType("text/plain; charset=utf-8");
                response.getWriter().write("文件不存在");
            }
        } catch (IOException e) {
            // 异常处理
            try {
                response.setContentType("text/plain; charset=utf-8");
                response.getWriter().write("下载失败：" + e.getMessage());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
